package com.fjh.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.fjh.domain.SysRole;
import com.fjh.dto.SysRoleDto;
import com.fjh.mapper.SysRoleMapper;
import com.fjh.service.SysRoleService;
import com.fjh.vo.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 查
     * @param dto
     * @return
     */
    @Override
    public PageInfo<SysRole> findByPage(SysRoleDto dto) {
        Page<Object> pageData = PageHelper.startPage(dto.getPage(), dto.getLimit());
        List<SysRole> data = sysRoleMapper.selectByPage(dto);
        return new PageInfo<SysRole>(pageData.getTotal(),data);
    }

    /**
     * 增
     * @param dto
     * @return
     */
    @Override
    public boolean save(SysRoleDto dto) {
        // 1 校验数据
        //2 属性拷贝
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(dto, sysRole);
        // 3 设置默认值
        return sysRoleMapper.insert(sysRole) > 0;
    }

    /**
     * 删
     * @param ids
     * @return
     */
    @Override
    public boolean batchDelete(Integer[] ids) {
        int row = sysRoleMapper.batchDelete(ids);
        return row == ids.length;
    }

    /**
     * 改
     * @param dto
     * @return
     */
    @Override
    public boolean update(SysRoleDto dto) {
        // 1 校验数据
        //2 属性拷贝
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(dto, sysRole);
        // 3 设置默认值
        return sysRoleMapper.updateByPrimaryKeySelective(sysRole) > 0;
    }

    @Override
    public List<SysRole> selectAllRoles() {
        return sysRoleMapper.selectAllRoles();
    }

    @Override
    public List<Integer> getUserRoleIds(Integer userId) {
        return sysRoleMapper.selectByUserId(userId);
    }

    /**
     * 分配权限
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public Boolean assign(Integer userId, Integer[] roleIds) {
        //1 删除旧值
        int row = sysRoleMapper.deleteByUserId(userId);
        // 2 创建新值
        sysRoleMapper.insertNewRoles(userId, roleIds);
        return row >= 0;
    }

    @Override
    public List<SysRole> findByUserId(Integer id) {
        return sysRoleMapper.selectRoleByUserId(id);
    }
}
